package com.kingyea.mobilepolice.util;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;

/**
 * @author cxc
 * @version v1.0.0
 * @description This is a class
 * @date Created in 2018.04.17 16:14
 */

public class RestTemplateUtils {


    public static String getAdminToken() {
        AccessTokenRequest atr = new DefaultAccessTokenRequest();
        OAuth2RestTemplate orest = new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));

        OAuth2AccessToken token = orest.getAccessToken();
        System.out.println(token);
        System.out.println(token.getRefreshToken());
        System.out.println(JSON.toJSONString(token));
        return token.toString();
    }

    protected static OAuth2ProtectedResourceDetails resource() {
//        ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
//        resource.setAccessTokenUri("http://192.168.0.66:8784/uaa/oauth/token");
//        resource.setClientId("auth-server");
//        resource.setClientSecret("auth-server");
//        resource.setScope(Lists.newArrayList("*"));
//        resource.setUsername("admin");
//        resource.setPassword("admin");
        ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
        //o.setGrantType("client_credentials");//default
        resource.setScope(Lists.newArrayList("gg"));
        resource.setAccessTokenUri("http://192.168.0.100:8784/uaa/oauth/token");
        resource.setClientId("auth-server");
        resource.setClientSecret("auth-server");
//        resource.setClientId("gg");
//        resource.setClientSecret("mm");
        return resource;
    }

    public static void main(String[] args) {
        String url = "http://192.168.0.66:8784/uaa/oauth/token";
        System.out.println(url.substring(url.indexOf("/", 7)));
        System.out.println(url.replaceFirst("localhost", "192.168.0.100"));
        System.out.println(url.replaceFirst("192.168.0.66", "192.168.0.100"));
    }
}
